package com.xgkj.diyiketang.activity;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.xgkj.diyiketang.ProtocolConst;
import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.data.EatShowUserInfo;
import com.xgkj.diyiketang.data.OrderInfo;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.http.engine.TaskEventListener;
import com.xgkj.diyiketang.task.BuildOrderTask;
import com.xgkj.diyiketang.task.GetUserDetailTask;
import com.xgkj.diyiketang.task.YueZhiFuTask;
import com.xgkj.diyiketang.util.DialogUtil;
import com.xgkj.diyiketang.util.ImageCache;
import com.xgkj.diyiketang.util.PalLog;
import com.xgkj.diyiketang.util.ToastUtil;
import com.xgkj.diyiketang.util.ViewUtil;
import com.xgkj.diyiketang.util.WeiXinPay;
import com.xgkj.eatshow.wxapi.WXPayEntryActivity;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * Created by XCKJ_Paladowow on 2016/8/11.
 */
public class OpenVipActivity extends BaseActivity implements View.OnClickListener {
    private Context mContext;
    private TextView back;
    private TextView mNickText;
    private TextView mSighText;
    private ImageView mUserLogo;
    EatShowUserInfo userInfo;
    private Button zhifuBtn;
    private RelativeLayout lingqianLayout;
    private RelativeLayout weixinLayout;
    private ImageView lingqian_check;
    private ImageView weixin_check;
    private int mZhifuType = 2;
    private int yuezhifuTaskId = -1;
    private int type = 1;
    private int orderTaskId = -1;
    private ProgressDialog mProgressDialog;
    private IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
    private BroadcastReceiver mWeiXinReceive;
    private String orderNo;
    private String orderBody = "购买vip";
    private TextView youhui;
    private RelativeLayout lvFiveLayout;
    private RelativeLayout lvFourLayout;
    private RelativeLayout lvThreeLayout;
    private RelativeLayout lvTwoLayout;
    private RelativeLayout lvOneLayout;
    private TextView lvFive;
    private TextView lvFour;
    private TextView lvThree;
    private TextView lvTwo;
    private TextView lvOne;
    private TextView payMoney;
    private EditText inviteCode;
    private int vip;
    private int detailTaskId = -1;
    private String code;
    private ImageView serviceContract;
    private boolean isAgree = true;
    private InputMethodManager im;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.open_vip);
        mContext = this;
        msgApi.registerApp(ProtocolConst.APP_ID);
        initView();
    }

    private void initView() {

        youhui = (TextView) findViewById(R.id.youhui_series_layout);
        youhui.setOnClickListener(this);

        lvFiveLayout = (RelativeLayout) findViewById(R.id.lv_five_vip_layout);
        lvFiveLayout.setOnClickListener(this);

        lvFourLayout = (RelativeLayout) findViewById(R.id.lv_four_layout);
        lvFourLayout.setOnClickListener(this);

        lvThreeLayout = (RelativeLayout) findViewById(R.id.lv_three_layout);
        lvThreeLayout.setOnClickListener(this);

        lvTwoLayout = (RelativeLayout) findViewById(R.id.lv_two_layout);
        lvTwoLayout.setOnClickListener(this);

        lvOneLayout = (RelativeLayout) findViewById(R.id.lv_one_layout);
        lvOneLayout.setOnClickListener(this);

        lvFive = (TextView) findViewById(R.id.lv_five);
        lvFive.setOnClickListener(this);

        lvFour = (TextView) findViewById(R.id.lv_four);
        lvFour.setOnClickListener(this);

        lvThree = (TextView) findViewById(R.id.lv_three);
        lvThree.setOnClickListener(this);

        lvTwo = (TextView) findViewById(R.id.lv_two);
        lvTwo.setOnClickListener(this);

        lvOne = (TextView) findViewById(R.id.lv_one);
        lvOne.setOnClickListener(this);

        inviteCode = (EditText) findViewById(R.id.edit_invite_code);
        payMoney = (TextView) findViewById(R.id.pay_money);

        back = (TextView) findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mUserLogo = (ImageView) findViewById(R.id.head_img);
        mNickText = (TextView) findViewById(R.id.user_nick);
        mSighText = (TextView) findViewById(R.id.user_sign);
        userInfo = getEatShowApp().getmUserInfo();
        if (userInfo != null) {
            String head_url = userInfo.getUserLogo();
            if (head_url != null && head_url.length() > 0) {
                ImageCache.getInstance(mContext).loadBitmapToView(mUserLogo, head_url, new ViewUtil.Size(ViewUtil.dip2px(mContext, 60), ViewUtil.dip2px(mContext, 60)));
            }

            try {
                if (!TextUtils.isEmpty(userInfo.getNickName())) {
                    mNickText.setText(URLDecoder.decode(userInfo.getNickName(), "utf-8"));
                }

                if (!TextUtils.isEmpty(userInfo.getUserSign())) {
                    mSighText.setText(URLDecoder.decode(userInfo.getUserSign(), "utf-8"));
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        lingqianLayout = (RelativeLayout) findViewById(R.id.lingqian_layout);
        lingqianLayout.setOnClickListener(this);
        lingqian_check = (ImageView) findViewById(R.id.lingqian_check);
        weixinLayout = (RelativeLayout) findViewById(R.id.weixin_layout);
        weixinLayout.setOnClickListener(this);
        weixin_check = (ImageView) findViewById(R.id.weixin_check);
        serviceContract = (ImageView) findViewById(R.id.service_contract);
        serviceContract.setOnClickListener(this);
        zhifuBtn = (Button) findViewById(R.id.zhifu_btn);
        zhifuBtn.setOnClickListener(this);
        type = 1;
        if (getIntent().getBooleanExtra("isVip", false)) {
            inviteCode.setVisibility(View.GONE);
        } else {
            code = String.valueOf(inviteCode.getText());
            inviteCode.setVisibility(View.VISIBLE);
        }

        im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

    }

    @Override
    protected void onResume() {
        super.onResume();
        isVip();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.youhui_series_layout:
                Intent intent = new Intent(OpenVipActivity.this, FuwuxieyActivity.class);
                startActivity(intent);
//               跳转到服务协议
                break;
            case R.id.lv_five_vip_layout:
                payMoney.setText(lvFive.getText());
                lvFiveLayout.setBackgroundColor(getResources().getColor(R.color.diliver));
                lvFourLayout.setBackgroundColor(getResources().getColor(R.color.white));
                lvThreeLayout.setBackgroundColor(getResources().getColor(R.color.white));
                lvTwoLayout.setBackgroundColor(getResources().getColor(R.color.white));
                lvOneLayout.setBackgroundColor(getResources().getColor(R.color.white));
                break;
            case R.id.lv_four_layout:
                payMoney.setText(lvFour.getText());
                lvFiveLayout.setBackgroundColor(getResources().getColor(R.color.white));
                lvFourLayout.setBackgroundColor(getResources().getColor(R.color.diliver));
                lvThreeLayout.setBackgroundColor(getResources().getColor(R.color.white));
                lvTwoLayout.setBackgroundColor(getResources().getColor(R.color.white));
                lvOneLayout.setBackgroundColor(getResources().getColor(R.color.white));
                break;
            case R.id.lv_three_layout:
                payMoney.setText(lvThree.getText());
                lvFiveLayout.setBackgroundColor(getResources().getColor(R.color.white));
                lvFourLayout.setBackgroundColor(getResources().getColor(R.color.white));
                lvThreeLayout.setBackgroundColor(getResources().getColor(R.color.diliver));
                lvTwoLayout.setBackgroundColor(getResources().getColor(R.color.white));
                lvOneLayout.setBackgroundColor(getResources().getColor(R.color.white));
                break;
            case R.id.lv_two_layout:
                payMoney.setText(lvTwo.getText());
                lvFiveLayout.setBackgroundColor(getResources().getColor(R.color.white));
                lvFourLayout.setBackgroundColor(getResources().getColor(R.color.white));
                lvThreeLayout.setBackgroundColor(getResources().getColor(R.color.white));
                lvTwoLayout.setBackgroundColor(getResources().getColor(R.color.diliver));
                lvOneLayout.setBackgroundColor(getResources().getColor(R.color.white));
                break;
            case R.id.lv_one_layout:
                payMoney.setText(lvOne.getText());
                lvFiveLayout.setBackgroundColor(getResources().getColor(R.color.white));
                lvFourLayout.setBackgroundColor(getResources().getColor(R.color.white));
                lvThreeLayout.setBackgroundColor(getResources().getColor(R.color.white));
                lvTwoLayout.setBackgroundColor(getResources().getColor(R.color.white));
                lvOneLayout.setBackgroundColor(getResources().getColor(R.color.diliver));
                break;
            case R.id.lv_five:
                payMoney.setText(lvFive.getText());
                lvFiveLayout.setBackgroundColor(getResources().getColor(R.color.diliver));
                lvFourLayout.setBackgroundColor(getResources().getColor(R.color.white));
                lvThreeLayout.setBackgroundColor(getResources().getColor(R.color.white));
                lvTwoLayout.setBackgroundColor(getResources().getColor(R.color.white));
                lvOneLayout.setBackgroundColor(getResources().getColor(R.color.white));
                break;
            case R.id.lv_four:
                payMoney.setText(lvFour.getText());
                lvFiveLayout.setBackgroundColor(getResources().getColor(R.color.white));
                lvFourLayout.setBackgroundColor(getResources().getColor(R.color.diliver));
                lvThreeLayout.setBackgroundColor(getResources().getColor(R.color.white));
                lvTwoLayout.setBackgroundColor(getResources().getColor(R.color.white));
                lvOneLayout.setBackgroundColor(getResources().getColor(R.color.white));
                break;
            case R.id.lv_three:
                payMoney.setText(lvThree.getText());
                lvFiveLayout.setBackgroundColor(getResources().getColor(R.color.white));
                lvFourLayout.setBackgroundColor(getResources().getColor(R.color.white));
                lvThreeLayout.setBackgroundColor(getResources().getColor(R.color.diliver));
                lvTwoLayout.setBackgroundColor(getResources().getColor(R.color.white));
                lvOneLayout.setBackgroundColor(getResources().getColor(R.color.white));
                break;
            case R.id.lv_two:
                payMoney.setText(lvTwo.getText());
                lvFiveLayout.setBackgroundColor(getResources().getColor(R.color.white));
                lvFourLayout.setBackgroundColor(getResources().getColor(R.color.white));
                lvThreeLayout.setBackgroundColor(getResources().getColor(R.color.white));
                lvTwoLayout.setBackgroundColor(getResources().getColor(R.color.diliver));
                lvOneLayout.setBackgroundColor(getResources().getColor(R.color.white));
                break;
            case R.id.lv_one:
                payMoney.setText(lvOne.getText());
                lvFiveLayout.setBackgroundColor(getResources().getColor(R.color.white));
                lvFourLayout.setBackgroundColor(getResources().getColor(R.color.white));
                lvThreeLayout.setBackgroundColor(getResources().getColor(R.color.white));
                lvTwoLayout.setBackgroundColor(getResources().getColor(R.color.white));
                lvOneLayout.setBackgroundColor(getResources().getColor(R.color.diliver));
                break;
            case R.id.edit_invite_code:

                break;
            case R.id.lingqian_layout:
                type = 2;
                lingqian_check.setVisibility(View.VISIBLE);
                weixin_check.setVisibility(View.GONE);
                break;
            case R.id.weixin_layout:
                type = 1;
                weixin_check.setVisibility(View.VISIBLE);
                lingqian_check.setVisibility(View.GONE);
                break;

            case R.id.zhifu_btn:
                code = String.valueOf(inviteCode.getText());
                if (type == 2) {
                    doYueZhifu();
                } else if (type == 1) {
                    getOrder();
                }
                break;
            case R.id.service_contract:
                if (isAgree == true) {
                    isAgree = false;
                    serviceContract.setImageResource(R.drawable.disagree);
                    zhifuBtn.setTextColor(getResources().getColor(R.color.gray));
                    zhifuBtn.setClickable(false);
                } else {
                    isAgree = true;
                    serviceContract.setImageResource(R.drawable.agree);
                    zhifuBtn.setTextColor(getResources().getColor(R.color.white));
                    zhifuBtn.setClickable(true);
                }
                break;

        }
    }

    private void isVip() {
        GetUserDetailTask task = new GetUserDetailTask();
        task.addListener(new MyListener(mContext));
        detailTaskId = getEatShowApp().getTaskManager().addTask(task);
    }

    private void getOrder() {
        showProgressDialog();
        BuildOrderTask orderTask = new BuildOrderTask(null, "2", payMoney.getText() + "", null, code,null,null,null,null,null,null);
        orderTask.addListener(new ZhiFuTaskEventListener(mContext));
        orderTaskId = getEatShowApp().getTaskManager().addTask(orderTask);
    }

    private void doYueZhifu() {
        if (yuezhifuTaskId != -1) {
            return;
        }
        YueZhiFuTask task = new YueZhiFuTask("", "2", payMoney.getText() + "", code);
        task.addListener(new ZhiFuTaskEventListener(mContext));
        yuezhifuTaskId = getEatShowApp().getTaskManager().addTask(task);
    }

    class ZhiFuTaskEventListener extends ShowToastTaskEventListener {

        public ZhiFuTaskEventListener(Context context) {
            super(context);
        }

        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);
            if (yuezhifuTaskId == taskId) {
                yuezhifuTaskId = -1;
                if (data != null) {
//                    odinfo = (OrderInfo) data;
//                    mOrderNo = odinfo.getOrderNo();
//                    Intent intent = new Intent(mContext, BaoMingChengGongActivity.class);
//                    intent.putExtra("ORDERNO", mOrderNo);
//                    intent.putExtra("FEE", mMoney);
//                    startActivity(intent);
                    ToastUtil.showMessage(mContext, "购买成功!");
                    finish();
                }
            } else if (orderTaskId == taskId) {
                dismissDialog();
                OrderInfo info = (OrderInfo) data;
                if (info != null) {
                    orderNo = info.getOrderNo();
                    doWeixinPay();
                }


            }
        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            super.handleTaskError(taskId, errorCode, errorMsg);
            if (yuezhifuTaskId == taskId) {
                yuezhifuTaskId = -1;
            } else if (taskId == orderTaskId) {
                dismissDialog();
            }
        }

        @Override
        public void handleTaskMessage(int taskId, Object data) {
            super.handleTaskMessage(taskId, data);
        }
    }

    private boolean checkInput() {

        if (mZhifuType == -1) {
            Toast.makeText(mContext, R.string.no_check_pay, Toast.LENGTH_SHORT)
                    .show();
            return false;
        }
        return true;
    }

    private void showProgressDialog() {
        if (mProgressDialog == null) {
            mProgressDialog = DialogUtil.showProgressDialog(mContext, getString(R.string.get_ordering), new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    getEatShowApp().getTaskManager().cancelTask(orderTaskId);
                }
            });
        }
    }

    private void dismissDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }

    private void doWeixinPay() {
        if (!msgApi.isWXAppSupportAPI() || !msgApi.isWXAppInstalled()) {
            ToastUtil.showMessage(mContext, R.string.need_weixin_app);
            return;
        }

        if (mWeiXinReceive == null) {
            mWeiXinReceive = new WeixinReceive();
            IntentFilter filter = new IntentFilter();
            filter.addAction(WXPayEntryActivity.WEIXIN_PAY_SUCCESS_ACTION);
            registerReceiver(mWeiXinReceive, filter);
        }
        new WeiXinPay(msgApi, OpenVipActivity.this, orderNo, orderBody, payMoney.getText() + "");
    }

    class WeixinReceive extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            boolean isSuccess = intent.getBooleanExtra(ProtocolConst.WEIXINPAY_SUCCESS, false);
            if (isSuccess) {
                ToastUtil.showMessage(mContext, "购买成功");
            }
            if (mWeiXinReceive != null) {
                unregisterReceiver(mWeiXinReceive);
                mWeiXinReceive = null;
            }
        }
    }

    private class MyListener extends ShowToastTaskEventListener {
        public MyListener(Context mContext) {
            super(mContext);
        }

        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            EatShowUserInfo info = (EatShowUserInfo) data;
            vip = info.isVip();

        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {

        }

        @Override
        public void handleTaskMessage(int taskId, Object data) {

        }
    }
}
